﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace FTBS.Controllers
{
    public class SupplierController : Controller
    {
        private UserBLO _userBLO = new UserBLO();
        private TheaterBLO _theaterBLO = new TheaterBLO();

        /// <summary>
        /// Display all suppliers
        /// </summary>
        /// <returns>list of suppliers</returns>
        /// <author>hungph</author>
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null 
                || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            List<User> listSupplier = new List<User>();
            listSupplier = _userBLO.DisplayAllSuppliers();

            ViewBag.NameSortParm = "theater_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {
                listSupplier = listSupplier.Where(supplier => supplier.FullName.ToUpper().Contains(searchString.ToUpper())
                                                  || supplier.Email.ToUpper().Contains(searchString.ToUpper())
                                                  || supplier.PhoneNumber.ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "fullname_desc":
                    if (isSortDescending == true)
                    {
                        listSupplier = listSupplier.OrderByDescending(staff => staff.FullName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listSupplier = listSupplier.OrderBy(staff => staff.FullName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "email_desc":
                    if (isSortDescending == true)
                    {
                        listSupplier = listSupplier.OrderByDescending(staff => staff.Email).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listSupplier = listSupplier.OrderBy(staff => staff.Email).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "phoneNumber_desc":
                    if (isSortDescending == true)
                    {
                        listSupplier = listSupplier.OrderByDescending(staff => staff.PhoneNumber).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listSupplier = listSupplier.OrderBy(staff => staff.PhoneNumber).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "status_desc":
                    if (isSortDescending == true)
                    {
                        listSupplier = listSupplier.OrderByDescending(staff => staff.IsActive).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listSupplier = listSupplier.OrderBy(staff => staff.IsActive).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listSupplier = listSupplier.OrderBy(staff => staff.FullName).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listSupplier.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// Render view Create
        /// </summary>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Create()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            ViewBag.UserName = null;
            ViewBag.Email = null;
            return View();
        }

        /// <summary>
        /// create a supplier
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        [HttpPost]
        public ActionResult Create(User user, HttpPostedFileBase file)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            if (_userBLO.CheckUsername(user))
            {
                ViewBag.UserName = user.UserName;
            }
            if (_userBLO.CheckEmail(user))
            {
                ViewBag.Email = user.Email;
            }
            if (ModelState.IsValid)
            {
                if (!_userBLO.CheckUsername(user) && !_userBLO.CheckEmail(user))
                {
                    if (file != null)
                    {
                        file.SaveAs(HttpContext.Server.MapPath("~/Image/SupplierImages/") + file.FileName);
                        user.ImageURL = file.FileName;
                    }
                    user.Password = _userBLO.GenerateMD5(user.Password);
                    ViewBag.UserName = null;
                    ViewBag.Email = null;
                    var isSuccess = _userBLO.CreateSupplier(user);
                    if (isSuccess)
                    {
                        return RedirectToAction("Index");
                    }
                    return View(user);
                }
            }
            return View(user);
        }

        /// <summary>
        /// load supplier and render view edit info of supplier
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Edit(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);

        }

        /// <summary>
        /// edit info of supplier
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            var email = _userBLO.LoadUserByUserName(user.UserName).Email;
            if (email == user.Email)
            {
                ViewBag.Email = null;
            }
            if (email != user.Email)
            {
                ViewBag.Email = user.Email;
            }
            if (ModelState.IsValid)
            {
                var isExist = _userBLO.CheckEmail(user);
                if (!isExist || (ViewBag.Email == null))
                {
                    user.Password = _userBLO.GenerateMD5(user.Password);
                    var isSuccess = _userBLO.EditSupplier(user);
                    if (isSuccess)
                    {
                        ViewBag.Email = null;
                        return RedirectToAction("Index");
                    }
                }
            }
            return View(user);
        }

        /// <summary>
        /// active supplier
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Active(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            bool isActive = _userBLO.ActiveUser(user);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// deactive user
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        public ActionResult Deactive(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            if (!_userBLO.IsUsed(user))
            {
                bool isActive = _userBLO.DeactiveUser(user);
                return RedirectToAction("Index");
            }
            TempData["IsUsed"] = true;
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Delete user
        /// </summary>
        /// <param name="id"></param>
        /// <returns>Redirect to Index page</returns>
        /// <author>hungph</author>
        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(String id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            if (!_userBLO.IsUsed(user)) { _userBLO.DeleteUser(user);
            return RedirectToAction("Index");
            }
            TempData["IsUsed"] = true;
            return RedirectToAction("Index");
        }

        /// <summary>
        ///  Show supplier detail
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>  
        /// <author>DuyHDV</author>  
        public ActionResult Detail(string id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Admin")
            {
                return Redirect("/Home/Announcement");
            }
            User supplier = _userBLO.LoadUserByUserName(id);
            return View(supplier);
        }
        /// <summary>
        ///  Show Supplier profile
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>  
        /// <author>DuyHDV</author>  
        public ActionResult Profile()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Supplier")
            {
                return Redirect("/Home/Announcement");
            }
            string id = Session["UserName"].ToString();
            User supplier = _userBLO.LoadUserByUserName(id);
            return View(supplier);
        }
        /// <summary>
        ///   Render edit profile page
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        /// <author>DuyHDV</author>   
        public ActionResult EditProfile(string id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Supplier")
            {
                return Redirect("/Home/Announcement");
            }
            User user = _userBLO.LoadUserByUserName(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            //ViewBag.Pwd = user.Password;
            return View(user);
        }
        /// <summary>
        ///    Result page of the Edit action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>DuyHDV</author>  
        [HttpPost]
        public ActionResult EditProfile(User user, HttpPostedFileBase file)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Supplier")
            {
                return Redirect("/Home/Announcement");
            }
            string username = user.UserName;
            User userData = _userBLO.LoadUserByUserName(username);
            if (user.Password == null)
            {
                user.Password = userData.Password;
            }
            bool isExisted = false;
            if (user.Email == userData.Email)
            {
                ViewBag.Email = null;
            }
            else
            {
                isExisted = _userBLO.CheckEmail(user);
                if (isExisted)
                {
                    ViewBag.Email = user.Email;
                }
            }
            if (ModelState.IsValid)
            {
                if (!isExisted && username == Session["UserName"].ToString())
                {
                    if (file != null)
                    {
                        if (file.FileName.Equals(userData.ImageURL))
                        {
                            file.SaveAs(HttpContext.Server.MapPath("~/Image/SupplierImages/") + file.FileName);
                            user.ImageURL = file.FileName;
                        }
                        else// if (!file.FileName.Equals(userData.ImageURL))
                        {
                            if (user.ImageURL != null)
                            {
                                System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/SupplierImages/") + userData.ImageURL);
                            }
                            file.SaveAs(HttpContext.Server.MapPath("~/Image/SupplierImages/") + file.FileName);
                            user.ImageURL = file.FileName;
                        }
                    }
                    else
                    {
                        user.ImageURL = userData.ImageURL;
                    }
                    user.IsActive = userData.IsActive;
                    user.IsDeleted = userData.IsDeleted;
                    var isSuccess = _userBLO.EditSupplier(user);
                    if (isSuccess)
                    {
                        this.Session["Account"] = user.FullName;
                        return RedirectToAction("Profile", new { id = username });
                    }
                }
            }
            return View(user);
        }

        /// <summary>
        /// load theaters of supplier
        /// </summary>
        /// <param name="sortOrder"></param>
        /// <param name="currentFilter"></param>
        /// <param name="searchString"></param>
        /// <param name="page"></param>
        /// <param name="isSortDescending"></param>
        /// <returns></returns>
        public ActionResult LoadTheater(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Supplier")
            {
                return Redirect("/Home/Announcement");
            }
            string username = this.Session["UserName"].ToString().Trim();
            List<Theater> listTheater = new List<Theater>();
            listTheater = _theaterBLO.GetAllTheatersByUsernameOfSupplier(username);

            ViewBag.NameSortParm = "theater_name_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {

                listTheater = listTheater.Where(theater => theater.TheaterName.ToUpper().Contains(searchString.ToUpper())
                                  || theater.Address.ToUpper().Contains(searchString.ToUpper())
                                  || theater.PhoneNumber.ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "theater_name_desc":
                    if (isSortDescending == true)
                    {
                        listTheater = listTheater.OrderByDescending(theater => theater.TheaterName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listTheater = listTheater.OrderBy(theater => theater.TheaterName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "address_desc":
                    if (isSortDescending == true)
                    {
                        listTheater = listTheater.OrderByDescending(theater => theater.Address).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listTheater = listTheater.OrderBy(theater => theater.Address).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "phone_desc":
                    if (isSortDescending == true)
                    {
                        listTheater = listTheater.OrderByDescending(theater => theater.PhoneNumber).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listTheater = listTheater.OrderBy(theater => theater.PhoneNumber).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listTheater = listTheater.OrderBy(theater => theater.TheaterName).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listTheater.ToPagedList(pageNumber, pageSize));
        }

        public ActionResult EditTheater(int id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Supplier")
            {
                return Redirect("/Home/Announcement");
            }
            Theater theater = _theaterBLO.GetTheaterById(id);
            ViewBag.TheaterName = null;
            if (theater == null)
            {
                return HttpNotFound();
            }
            return View(theater);
        }

        /// <summary>
        /// Event Create new Theater
        /// </summary>
        /// <param name="theater"></param>
        /// <param name="fileImageUpdate"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditTheater(Theater theater, HttpPostedFileBase fileImageUpdate)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Supplier")
            {
                return Redirect("/Home/Announcement");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    Theater theaterEntity = new Theater();
                    theaterEntity = _theaterBLO.GetTheaterById(theater.TheaterId);
                    if (!theater.TheaterName.Equals(theaterEntity.TheaterName))
                    {
                        if (!_theaterBLO.IsExistTheaterUpdate(theater))
                        {
                            if (fileImageUpdate != null)
                            {
                                if (fileImageUpdate.FileName.Equals(theaterEntity.ImageURL))
                                {
                                    fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                                    theater.ImageURL = fileImageUpdate.FileName;
                                }
                                else if (!fileImageUpdate.FileName.Equals(theaterEntity.ImageURL))
                                {
                                    if (theater.ImageURL != null)
                                    {
                                        System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/Theater/") + theaterEntity.ImageURL);
                                    }
                                    fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                                    theater.ImageURL = fileImageUpdate.FileName;
                                }
                            }

                            ViewBag.TheaterName = null;
                            _theaterBLO.EditTheater(theater);
                            return RedirectToAction("LoadTheater");
                        }
                        else
                        {
                            ViewBag.TheaterName = theater.TheaterName;
                            return View(theater);
                        }
                    }
                    else
                    {
                        if (fileImageUpdate != null)
                        {
                            if (fileImageUpdate.FileName.Equals(theaterEntity.ImageURL) || string.Empty.Equals(theaterEntity.ImageURL))
                            {
                                fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                                theater.ImageURL = fileImageUpdate.FileName;
                            }
                            else if (!fileImageUpdate.FileName.Equals(theaterEntity.ImageURL))
                            {
                                if (theater.ImageURL != null)
                                {
                                    System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/Theater/") + theaterEntity.ImageURL);
                                }
                                fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                                theater.ImageURL = fileImageUpdate.FileName;
                            }
                        }

                        ViewBag.TheaterName = null;
                        _theaterBLO.EditTheater(theater);
                        return RedirectToAction("LoadTheater");
                    }
                }
                catch (Exception)
                {

                    ViewBag.TheaterName = theater.TheaterName;
                    return View(theater);
                }
            }
            else
            {
                ViewBag.TheaterName = theater.TheaterName;
                return View(theater);
            }
        }
    }
}
